// pages/cart/cart.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    height: app.globalData.navBarHeight + app.globalData.statusBarHeight,
    statusBarHeight: app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,
    totalSelected: false,
    cartList: [],
    totalCount: 0,
    totalPrice: "0.00"
  },

  getCartList() {
    wx.request({
      url: 'http://localhost:8082/app/omsGoodsCart/pagination',
      method: "GET",
      data: {},
      success: (res) => {
        res = res.data;
        if (res.code != 200) {
          return;
        }
        let data = res.data;
        let list = data;
        let totalSelected = true;
        list = list.map(item => {
          let goodsInfo = item.goodsInfo || {};
          let actualPrice = goodsInfo.actualPrice + "";
          if (!item.selected) {
            totalSelected = false;
          }
          return {
            ...item,
            selected: item.selected ? true : false,
            name: goodsInfo.name,
            coverUrl: goodsInfo.coverUrl,
            actualPrice: actualPrice,
            actualIntPrice: actualPrice.substring(0, actualPrice.length - 2),
            actualFloatPrice: actualPrice.substring(actualPrice.length - 2)
          }
        })

        this.calcTotalPrice(list.filter(item => item.selected));
        this.setData({
          cartList: list,
          totalSelected
        })
      },
      fail: (err) => {
        console.error("2222", err)
      }
    })
  },

  addCart(cartList = []) {
    cartList = cartList.map(item => {
      return {
        ...item,
        selected: item.selected ? 1 : 0
      }
    })
    wx.request({
      url: 'http://localhost:8082/app/omsGoodsCart/updateAmountAndStatus',
      method: "PUT",
      data: [...cartList],
      success: (res) => {
        console.log("addCart: ", res);
        this.setData({
          cartCount: this.data.cartCount + 1
        })
      },
      fail: (err) => {
        console.error("2222", err)
      }
    })
  },

  countPlus(event) {
    let goodsItem = event.currentTarget.dataset.item || {};
    let cartList = this.data.cartList || [];
    let findRes = cartList.find(item => {
      return goodsItem.id == item.id;
    })
    if (findRes) {
      findRes.amount++;
      this.setData({
        cartList: cartList.slice()
      });
      this.addCart([{
        cartId: findRes.id,
        selected: findRes.selected,
        amount: findRes.amount
      }]);
    }
    //如果是已选择的商品，则需要重新计算价格
    if (findRes.selected) {
      this.calcTotalPrice(cartList.filter(item => item.selected));
    }
  },

  countMinus(event) {
    let goodsItem = event.currentTarget.dataset.item || {};
    let cartList = this.data.cartList || [];
    let findRes = cartList.find(item => {
      return goodsItem.id == item.id;
    })
    if (findRes && findRes.amount > 1) {
      findRes.amount--;
      this.setData({
        cartList: cartList.slice()
      });
      this.addCart([{
        cartId: findRes.id,
        selected: findRes.selected,
        amount: findRes.amount
      }]);
    }
    //如果是已选择的商品，则需要重新计算价格
    if (findRes.selected) {
      this.calcTotalPrice(cartList.filter(item => item.selected));
    }
  },

  checkboxChange(event) {
    console.log("data: ", event.detail.value);
    let dataList = event.detail.value;
    let cartList = this.data.cartList || [];
    //先全部选择取消选中
    cartList = cartList.map(row => {
      row.selected = false;
      return row;
    })
    for (let index in dataList) {
      let item = dataList[index];
      let findRes = cartList.find(row => {
        return row.id == item;
      })
      //表明这个是选中的
      if (findRes) {
        findRes.selected = true;
      }
    }

    this.addCart(
      cartList.map(findRes => {
        return {
          cartId: findRes.id,
          selected: findRes.selected,
          amount: findRes.amount
        }
      }));
    let selectedCartList = cartList.filter(item => item.selected);
    this.calcTotalPrice(selectedCartList);
    let totalSelected = selectedCartList.length == cartList.length;
    this.setData({
      cartList,
      totalSelected
    })
  },

  calcTotalPrice(selectedCartList = []) {
    let totalPrice = 0;
    let totalCount = 0;
    selectedCartList.forEach(item => {
      item.selected = true;
      //计算总价格
      totalCount += item.amount;
      totalPrice += item.actualPrice * item.amount;
    });
    let strTotlePrice = totalPrice + '';
    let totalIntPrice = strTotlePrice.substring(0, strTotlePrice.length - 2);
    let totalFloatPrice = strTotlePrice.substring(strTotlePrice.length - 2);
    this.setData({
      totalCount,
      totalPrice: totalPrice == 0 ? '0.00' : `${totalIntPrice}.${totalFloatPrice}`
    })
  },

  allCheckboxChange(event) {
    let totalSelected = false;
    let cartList = this.data.cartList || [];
    if (event.detail.value.length > 0) {
      totalSelected = true;
      cartList.map(item => {
        item.selected = true;
        return item;
      });
    } else {
      cartList.map(item => {
        item.selected = false;
        return item;
      });
    }
    //计算价格
    this.addCart(
      cartList.map(findRes => {
        return {
          cartId: findRes.id,
          selected: findRes.selected,
          amount: findRes.amount
        }
      }));
    let selectedCartList = cartList.filter(item => item.selected);
    this.calcTotalPrice(selectedCartList);
    this.setData({
      cartList,
      totalSelected
    })
  },

  toPaymentPage() {
    wx.navigateTo({
      url: '/pages/payment/payment',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getCartList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})